package alt.fr.ma.np.activities;

import alt.fr.ma.np.soap.SOAPRequest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

public class SociablonActivity extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("NORMAL - SociablonActivity", "Starting SociablonActivity!");
		userAuthentication();
	}

	private void userAuthentication() {

		Boolean authenticated = false;

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);

		String login = preferences.getString("login", null);
		String password = preferences.getString("password", null);

		Log.d("NORMAL - SociablonActivity",
				"Checking for existing user authentication...");

		if (login != null && password != null) {

			Log.d("NORMAL - SociablonActivity",
					"User authentication found, logging in...");

			SOAPRequest SOAPRequest = new SOAPRequest("sociablon", login,
					password, "WSLogin");

			// Starting the SOAP request and waiting for the response
			Thread request = new Thread(SOAPRequest);
			request.start();

			try {
				request.join();
			} catch (InterruptedException e) {
				Log.d("ERROR - SociablonActivity", "InterruptedException", e);
			}

			String soapResponse = null;
			try {
				soapResponse = SOAPRequest.getSOAPResponse();
			} catch (Exception e) {
				Log.d("ERROR - SociablonActivity", "SOAPResponseException", e);
			}

			if (soapResponse != null) {
				Log.d("NORMAL - SociablonActivity", "SOAPResponse = "
						+ soapResponse);

				if (soapResponse.contains("Welcome"))
					authenticated = true;
			}
		}

		// If the user is already authenticated we start the main activity
		if (authenticated) {
			Log.d("NORMAL - SociablonActivity",
					"User successfully authenticated.");
			startActivity(new Intent(this, MainActivity.class));
		}

		// Else we start the login activity
		else {
			Log.d("NORMAL - SociablonActivity", "User not authenticated.");
			startActivity(new Intent(this, LoginActivity.class));
		}
	}
}